%option prefix="url_yy"

%x host
%x port
%x path

%{
#define _BSD_SOURCE

#include <string.h>
#include <stdlib.h>

static char *scheme_b, *host_b, *path_b;
static int port_b;

%}

%%

[a-z]+				{ strcpy(scheme_b, yytext); }
:\/\/				{ BEGIN(host); }
<host>[a-z0-9\-\.]+ { strcpy(host_b, yytext); }
<host>:				{ BEGIN(port); }
<host>\/			{ strcpy(path_b, "/"); BEGIN(path); }
<port>[0-9]+		{ port_b=atoi(yytext); }
<port>\/			{ strcpy(path_b, "/"); BEGIN(path); }
<path>[^\?]+		{ strcat(path_b, yytext); yyterminate(); }

<<EOF>>		{ yyterminate(); }


%%
 
int url_yywrap(void){return 1;}

int parse_url(char *url, char *_scheme, char *_host, int *_port, char *_path){
	scheme_b=_scheme;
	host_b=_host;
	path_b=_path;
	
	strcpy(scheme_b, "");
	strcpy(path_b, "");
	strcpy(host_b, "");
	port_b = 0;

	//reset_lexer();
	YY_BUFFER_STATE b = url_yy_scan_string(url);
	url_yy_switch_to_buffer(b);
	url_yylex();
	url_yy_delete_buffer(b);
	
	*_port = port_b;
}

/*
main(){
	char _scheme[10];
	char _host[100];
	char _path[500];
	int _port;
	
	parse_url("http://127.0.0.1:51234/a/b/c", _scheme, _host, &_port, _path);
	
	printf("scheme=%s\nhost=%s\nport=%i\npath=%s\n", scheme_b, _host, _port, _path);
	
}
*/
